package com.rjt.article.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.rjt.article.dto.ArticleVisitDto;
import com.rjt.article.model.ArticleFriendsShareModel;
import com.rjt.article.repository.ArticleFriendsShareRepository;
import com.rjt.article.service.ArticleFriendsShareService;
import com.rjt.article.vo.ArticleVisitVo;
import com.rjt.common.model.Address;
import com.rjt.common.util.TextUtil;
@Service
public class ArticleFriendsShareServiceImpl implements ArticleFriendsShareService {
	
	
	@Autowired
	private ArticleFriendsShareRepository articleFriendsShareRepository;
	
	
	@Override
	public void save(String rId, HttpServletRequest request) {
		// TODO Auto-generated method stub
		try {
			ArticleFriendsShareModel articleFriendsShare = new ArticleFriendsShareModel();
			articleFriendsShare.setrId(rId);
			articleFriendsShare.setCreateDate(new Date());
			String remortIP = TextUtil.getRemortIP(request);
			System.out.println("类ArticleFriendsShareServiceImpl获取的远端的ip"+remortIP);
			if(Objects.isNull(remortIP)) {
				return ;
			}
			articleFriendsShare.setIp(remortIP);
			Address place = TextUtil.getPlace(remortIP);
			articleFriendsShare.setRegion(place.getProvince());
			articleFriendsShare.setCity(place.getCity());
			articleFriendsShareRepository.save(articleFriendsShare);
		} catch (Exception e) {
			// TODO: handle exception
			System.out.println("保存朋友失败了,可能是重复的ip,错误代码"+e.getMessage());
		}
		
	}
	@Override
	public List<ArticleVisitVo> countByRIdAndArea(String rId) {
		// TODO Auto-generated method stub
		 List<ArticleVisitVo> countByArea =new ArrayList<>();
		 List<ArticleVisitDto> countByRIdAndArea = articleFriendsShareRepository.countByRIdAndArea(rId);
		 countByRIdAndArea.forEach(dto->{
			 ArticleVisitVo articleVisitVo = new ArticleVisitVo();
			 articleVisitVo.setName(dto.getRegion()+dto.getCity());
			 articleVisitVo.setValue(dto.getValue());
			 countByArea.add(articleVisitVo);
		 });
		 return countByArea;
		
	}
	
	@Override
	public List<ArticleVisitVo> countByRIdAndDate(String rId) {
		// TODO Auto-generated method stub
		 List<ArticleVisitVo> countByDate =new ArrayList<>();
		 List<ArticleVisitDto> countByRIdAndDate = articleFriendsShareRepository.countByRIdAndDate(rId);
		 countByRIdAndDate.forEach(dto->{
			 ArticleVisitVo articleVisitVo = new ArticleVisitVo();
			 articleVisitVo.setName(dto.getCreateDate());
			 articleVisitVo.setValue(dto.getValue());
			 countByDate.add(articleVisitVo);
		 });
		 return countByDate;
	}
	
   
}
